package com.tanhua.sso.service;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.tanhua.sso.config.AliyunSMSConfig;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @title: SendSmsService
 * @Author TGE
 * @Date: 2021/5/8 12:31
 * @Version 1.0
 */
@Service
@Slf4j
public class SmsService {
    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 发送短信验证码
     *
     * @param mobile
     * @return
     */
    public String sendSms(String mobile) {
        //随机六位数字
        String  code = String.valueOf(RandomUtils.nextInt(100000,999999));
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(this.aliyunSMSConfig.getAccessKeyId())
                // 您的AccessKey Secret
                .setAccessKeySecret(this.aliyunSMSConfig.getAccessKeySecret());
        // 访问的域名
        config.endpoint = this.aliyunSMSConfig.getDomain();
        try {
            Client client = new Client(config);
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile)
                    .setSignName(this.aliyunSMSConfig.getSignName())
                    .setTemplateCode(this.aliyunSMSConfig.getTemplateCode())
                    .setTemplateParam("	{\"code\":\""+code+"\"}");
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            if ("OK".equals(sendSmsResponse.getBody().code)){
                return code;
            }
            log.info("发送短信验证码失败~ data = " + sendSmsResponse.getBody().message);
        } catch (Exception e) {
            log.error("发送短信验证码失败~ mobile = " + mobile, e);
        }
        return null;

    }
    /**
     * 发送短信验证码
     * 实现：发送完成短信验证码后，需要将验证码保存到redis中
     * @param phone
     * @return
     */
    public ErrorResult sendCheckCode(String phone) {
        String redisKey = "CHECK_CODE_" + phone;
        if (redisTemplate.hasKey(redisKey)) {
            String msg="上一次的验证码还未失效！";
            return ErrorResult.builder().errCode("000000").errMessage(msg).build();
        }
        //String code = sendSms(phone);
        //随机六位数字 模拟发送验证码信息
        String  code = "123456";
        if (StringUtils.isEmpty(code)){
            String msg="验证码发送失败！";
            return ErrorResult.builder().errCode("000001").errMessage(msg).build();
        }
        //短信发送成功，将验证码保存到redis中，有效期为5分钟
        redisTemplate.opsForValue().set(redisKey,code, Duration.ofMinutes(10));

        //redisTemplate.boundValueOps(redisKey).set(code,10, TimeUnit.MINUTES);

        return null;
    }
}
